package br.com.serctam.servlet;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.persistence.HibernateSessionProxy;

import br.com.serctam.entity.BoletoPdf;

/**
 * Servlet implementation class BuscaBoletoServlet
 */
@Name("BuscaBoletoServlet")
public class BuscaBoletoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	
    @RequestParameter
    private Long idCandidato;
    
    @In
    private HibernateSessionProxy hibernateSession;

	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BuscaBoletoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
//        log.info("BuscaBoleto.buscaBoleto() action called: idCandidato" + idCandidato);
//        statusMessages.add("buscaBoleto");
        
		Query query = hibernateSession.createQuery(" select b from BoletoPdf b where b.id =  " + idCandidato );
		
        BoletoPdf boletoPdf = (BoletoPdf)query.uniqueResult();
        System.out.println(boletoPdf.getBoletopdf().length);
        
//        FacesContext facesContext = FacesContext.getCurrentInstance();
//        HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse();
        
        response.setContentType("application/pdf");
        response.setBufferSize(boletoPdf.getBoletopdf().length);
        response.setContentLength(boletoPdf.getBoletopdf().length);
        try {
        	response.getOutputStream().flush();
        	response.getOutputStream().write(boletoPdf.getBoletopdf());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
